import Datastore from 'nedb-promises'
import delete_unused_keys from './delete_unused_keys'

/**
 * 查询数据 包含要素：数据条数、数据
 * @param db
 * @param queryParams 包含 pagination 参数（分页）和 keyword 参数（模糊搜索）以及排序参数，sort 类型为 SortListType
 * @param resJSON
 * @param callback
 */
const SearchData = (db: Datastore<{ _id: string; }>, queryParams: any, resJSON: ResponseDataType, callback?: Function) => {

  const {
    filterKeyList = [], // 例如 ['value', 'label', 'key']
    keyword = '',
    sort = [{ key: 'id', order: 1 }],
    pageSize = 10,
    current = 1,
    paging = true,
    needsKeys = [],
    ...primaryQueryParams
  } = queryParams

  let searchParams: { [key: string]: any } = {}
  keyword && filterKeyList.map((item: string) => {
    searchParams[item] = { $regex: new RegExp(keyword) }
  })
  let sortParams: { [key: string]: 1 | -1 } = {}
  sort.map((item: SortItemType) => {
    sortParams[item.key] = item.order
  })

  // 处理数据的函数
  const dealData = async (res: any[]) => {
    console.log('search total', res.length)
    res = delete_unused_keys(res)
    if (typeof queryParams.id === 'string' && queryParams.id && res.length === 0) {
      resJSON.note = `id为 ${queryParams.id} 的记录不存在`
      callback && callback(resJSON)
    } else {
      resJSON = {
        code: 1,
        note: '查询成功',
        data: res,
        total: (await db.find({ ...primaryQueryParams, ...searchParams, _del: false })).length
      }
      callback && callback(resJSON)
    }
  }

  // 如果有分页参数则按照分页查询
  if (paging) {
    console.log('AllQueryParams', {...primaryQueryParams, ...searchParams})
    db.find({ ...primaryQueryParams, ...searchParams, _del: false })
      .sort(sortParams)
      .skip((current - 1) * pageSize)
      .limit(pageSize).then((res) => {
        dealData(res)
        console.log('res', res)
      }).catch((error) => {
        console.log(error)
        resJSON.note = error
        callback && callback(resJSON)
      })
  } else {
    db.find({ ...primaryQueryParams, ...searchParams, _del: false })
      .sort(sortParams)
      .then((res: any) => {
        dealData(res)
      }).catch((error) => {
        console.log(error)
        resJSON.note = error
        callback && callback(resJSON)
      })
  }
}

const SearchDataSync = async (db: Datastore<{ _id: string; }>, queryParams: any, resJSON: ResponseDataType) => {

  const {
    filterKeyList = [], // 例如 ['value', 'label', 'key']
    keyword = '',
    sort = [{ key: 'id', order: 1 }],
    pageSize = 10,
    current = 1,
    paging = true,
    ...primaryQueryParams
  } = queryParams

  const searchParams = filterKeyList.map((item: string) => {
    return { [item]: { $regex: keyword } }
  })
  let sortParams: { [key: string]: 1 | -1 } = {}
  sort.map((item: SortItemType) => {
    sortParams[item.key] = item.order
  })

  const dealData = async (res: any[]) => {
    console.log('sync search total', res.length)
    res = delete_unused_keys(res)
    if (queryParams.id && res.length === 0) {
      resJSON.note = `id为 ${queryParams.id} 的记录不存在`
    } else {
      resJSON = {
        code: 1,
        note: '查询成功',
        data: res,
        total: (await db.find({ ...primaryQueryParams, ...searchParams, _del: false })).length
      }
    }
  }

  // 如果有分页参数则按照分页查询
  if (paging) {
    await db.find({ ...primaryQueryParams, ...searchParams, _del: false })
      .sort(sortParams)
      .skip((current - 1) * pageSize)
      .limit(pageSize)
      .then(async (res: any) => {
        dealData(res)
      }).catch((error) => {
        resJSON.note = error
      })
  } else {
    await db.find({ ...primaryQueryParams, ...searchParams, _del: false })
      .sort(sortParams)
      .then(async (res: any) => {
        dealData(res)
      }).catch((error) => {
        resJSON.note = error
      })
  }
  return resJSON
}

export {
  SearchData,
  SearchDataSync,
}